package com.sto.stoapp.db.manager;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

public class KailiAftermarketManager extends StoDataBase {

	private final String SQL_QUERY_ALL = "select * from " + KAILI_AFTERMARKET_TABLE
			+ " where 1=1";
	
	public KailiAftermarketManager(Context context) {
		super(context);
	}

	/**
	 * 删除所有数据
	 * 
	 * @return
	 */
	public boolean deleteAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(KAILI_AFTERMARKET_TABLE, null, null);
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}
	
	/**
	 * 插入单条数据
	 * 
	 * @param entity
	 * @return
	 */
	public boolean insert(String info) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;

			try {
				ContentValues values = new ContentValues();
				values.put(KAILI_AFTERMARKET_INFO, info);
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.insert(KAILI_AFTERMARKET_TABLE, null, values);
				if (res > 0) {
					Log.d("插入一条凯立售后信息", "成功");
				} else {
					Log.d("插入一条凯立售后信息", "失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insert", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}
	
	/**
	 * 查询所有数据
	 * 
	 * @return
	 */
	public String queryAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(SQL_QUERY_ALL,
					null));
			return data;
		}
	}

	private String getDataFromCursor(final Cursor c) {
		String lstData = null;
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					lstData = c.getString(c.getColumnIndex(KAILI_AFTERMARKET_INFO));
				} while (c.moveToNext());
			}
			closeCursor(c);
		}
		closeDb(UnifiedStaticType.READ_DATABASE);
		return lstData;
	}

}
